<?php
/**
 * Auther: Joshua Conero
 * Date: 2017/11/12 0012 15:45
 * Email: brximl@163.com
 * Name:
 */

namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\LgRecord as LgRecordMd;
use app\common\model\LgProject;
use think\Db;

class Lgrecord extends Api
{
    const v_bindDataMk = '__bind_data';
    // 数据保存
    public function save(){
        $check = $this->needLoginNet($uid);
        if($check) return $check;
        list($data,$mode,$map) = $this->_getSaveData('no');
        //debugOut([$data,$mode,$map]);
        $logP = new LgRecordMd();
        switch ($mode){
            case 'A':
                $data['no'] = $logP->getNoVal();
                if($logP->save($data)){
                    return $this->FeekMsg('日志新增成功', 1);
                }
                return $this->FeekMsg('日志新增成功失败');
                break;
            case 'M':
                if($logP->save($data,$map)) return $this->FeekMsg('日志更新成功！',1);
                return $this->FeekMsg('日志更新失败！');
                break;
            case 'D':
                if($this->pushRptBack($logP->getTable(),$map,'auto'))
                    return $this->FeekMsg('日志删除成功！',1);
                return $this->FeekMsg('日志删除失败！');
                break;
        }
        return $this->FeekMsg('请求参数无效');
    }
    /**
     * 条件解析
     * @return array|bool
     */
    protected function parseWhere(){
        $where = '';
        $bind = [];
        //$args = $this->request->param('args');
        $args = isset($_POST['args'])? $_POST['args']: false;
        /**
        //args => {col: 键值, value: 值, equal: 等式, type: 类型}
        args => {c: 键值, v: 值, e: 等式, t:类型}
         **/
        if($args && is_array($args)){
            $t = isset($args['t'])? $args['t']:false;
            if($t){
                switch ($t){
                    case 'GROUP':   // 分组查询
                        // 按月分组
                        if($args['c'] == 'M1'){
                            $where = 'date_format(`date`, \'%Y-%m\') =: v_date';
                        }elseif($args['c'] == 'Y1'){
                            $where = 'date_format(`date`, \'%Y\') =: v_date';
                        }elseif($args['c'] == 'D1'){
                            $where = '`date` =: v_date';
                        }
                        $bind['v_date'] = $args['v'];
                        $where = [self::v_bindDataMk => true, 'data' => [$where, $bind]];
                        break;
                }
            // 条件查询
            }else if(isset($args['e'])){
                $e = $args['e'];
                $v = $args['v'];
                $c = $args['c'];
                switch ($e){
                    case 'like':$where[] = [$c, 'like', "%$v%"];break;
                    case 'begin':$where[] = [$c, 'like', "%$v"];break;
                    case 'end':$where[] = [$c, 'like', "$v%"];break;
                    default:
                        $where[$c] = $v;
                }
            }
        }
        return empty($where)? false: $where;
    }
    // 读取数据列表
    public function data(){
        $check = $this->needLoginNet($uid);
        if($check) return $check;
        $page = $this->request->param('page', 1);
        $num = $this->request->param('num', 15);
        $item = $this->request->param('item', 15);
        /*
        $rs = Db::table((new LgRecordMd())->getTable())
            ->alias('a')
            ->join([(new LgProject())->getTable() => ' b'], 'a.p_listid=b.listid')
            ->where('b.listid', $item)
            ->page($page, $num)
            ->select()
            ;
        */
        $where = $this->parseWhere();
        if(!$where) $where = [];
        // 关联对象查询
        $logP = LgProject::get($item);
        if($logP){
            $logP = $logP->Records();
        }
        if($logP){
            if(isset($where[self::v_bindDataMk])){
                $count = $logP
                    ->whereRaw($where['data'][0], $where['data'][1])
                    ->count();
            }else{
                $count = $logP
                    ->where($where)
                    ->count();
            }
        }else{
            $count = 0;
        }
        $rs = $logP?
            $logP->where($where)
                ->page($page, $num)
                ->order('date desc')
                ->select()
            :
            null
            ;
//        if($rs && is_object($rs) && method_exists($rs, 'toArray')){
//            $rs = $rs->toArray();
//        }
        return $this->FeekMsg([
            'result' => $rs,
            'count'  => $count,
            'page'   => $page,
            'num'    => $num
        ]);
    }
    // 读取分组
    public function group(){
        $check = $this->needLoginNet($uid);
        if($check) return $check;
        $page = $this->request->param('page', 1);
        $num = $this->request->param('num', 15);
        $table = false;
        $lgR = new LgRecordMd();
        $type = $this->request->param('type');
        $count = 0;
        switch ($type){
            case 'D1':
                $table = Db::table($lgR->getTable())
                    ->alias('a')
                    ->join(['log_project'=>'b'], 'a.p_listid=b.listid')
                    ->field(['date'=>'item', 'count(*)'=>'count'])
                    ->where(['b.uid'=>$uid])
                    ->group('date')
                    ->order('a.date desc')
                    ->select(false)
                ;
                $table = "($table)";
                $ctDt = Db::query('select count(*) as `count`from '.$table.' a');
                if($ctDt){
                    $count = $ctDt[0]['count'];
                }
                //debugOut($table);
                break;
            case 'M1':
                $table = Db::table($lgR->getTable())
                    ->alias('a')
                    ->join(['log_project'=>'b'], 'a.p_listid=b.listid')
                    ->field(['date_format(a.`date`, \'%Y-%m\')'=>'item', 'count(*)'=>'count'])
                    ->where(['b.uid'=>$uid])
                    ->group('date_format(a.`date`, \'%Y-%m\')')
                    ->order('a.date desc')
                    ->select(false)
                    ;
                $table = "($table)";
                $ctDt = Db::query('select count(*) as `count`from '.$table.' a');
                if($ctDt){
                    $count = $ctDt[0]['count'];
                }
                //debugOut($table);
                break;
            case 'Y1':
                $table = Db::table($lgR->getTable())
                    ->alias('a')
                    ->join(['log_project'=>'b'], 'a.p_listid=b.listid')
                    ->field(['date_format(a.`date`, \'%Y\')'=>'item', 'count(*)'=>'count'])
                    ->where(['b.uid'=>$uid])
                    ->group('date_format(a.`date`, \'%Y\')')
                    ->order('a.date desc')
                    ->select(false)
                ;
                $table = "($table)";
                $ctDt = Db::query('select count(*) as `count`from '.$table.' a');
                if($ctDt){
                    $count = $ctDt[0]['count'];
                }
                //debugOut($table);
                break;
        }
        $rs = false;
        if($table){
            $sql = 'select * from '.$table.' a limit '.($num*($page-1)).','.$num;
            //debugOut($sql);
            $rs = Db::query($sql);
        }
        if($rs){
            return $this->FeekMsg([
                'rs'    => $rs,
                'count' => $count,
                'page'  => $page,
                'num'   => $num
            ]);
        }
        return $this->FeekMsg('分组获取失败');
    }
}